package bank;

import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

public class BankService {
    Map<String, Account> accounts;
    List<TransactionRecord> transactionRecords;

    public BankService(Map<String, Account> accounts, List<TransactionRecord> transactionRecords) {
        this.accounts = accounts;
        this.transactionRecords = transactionRecords;
    }
    public void BankService() {
    }
    //执行一条交易记录，并更新账户余额。同时，将该记录添加到交易日志列表中。
    public void executeTransaction(TransactionRecord record) {

        Account account = accounts.get(record.getAccountNumber());
        if (account != null) {
            account.setBalance(record.getPostBalance());
        }
        transactionRecords.add(record);

    }
    public void exportAuditLog(String accountNumber, LocalDateTime start, LocalDateTime end, String filePath) {
        double totalIncome = 0;
        double totalExpense = 0;

        // 先筛选并计算统计数据
        for (TransactionRecord record : transactionRecords) {
            if (record.getAccountNumber().equals(accountNumber)
                    && record.getTimestamp().isAfter(start)
                    && record.getTimestamp().isBefore(end)) {

                // 修正枚举类型判断
                if (record.getType() == TransactionType.DEPOSIT || record.getType() == TransactionType.TRANSFER_IN) {
                    totalIncome += record.getAmount();
                } else if (record.getType() == TransactionType.WITHDRAW || record.getType() == TransactionType.TRANSFER_OUT) {
                    totalExpense += record.getAmount();
                }
            }
        }

        // 循环外打印统计结果
        System.out.println("Total Income: " + totalIncome);
        System.out.println("Total Expense: " + totalExpense);

        // 写入CSV文件的逻辑（略）
        try {
            // 使用传入的filePath参数，而非硬编码路径
            FileWriter writer = new FileWriter(filePath);
            writer.write("TransactionTime,Type,Amount,CounterpartyAccount,PostBalance\n");
            for (TransactionRecord record : transactionRecords) {
                if (record.getAccountNumber().equals(accountNumber)
                        && record.getTimestamp().isAfter(start)
                        && record.getTimestamp().isBefore(end)) {
                    writer.write(record.getTimestamp() + ","
                            + record.getType() + ","
                            + record.getAmount() + ","
                            + record.getCounterpartyAccount() + ","
                            + record.getPostBalance() + "\n");
                }
            }
            writer.close(); // 必须关闭流才能写入数据
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
